package com.rongzhe.house.common.utils;

import com.rongzhe.house.common.cache.CommonCacheUtil;
import com.rongzhe.house.common.constants.Constants;
import com.rongzhe.house.common.exception.RongZheBusinessException;
import com.rongzhe.house.user.entity.UserElement;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>Description:   </p>
 * <p>email: ypasdf@163.com</p>
 * <p>Copyright: Copyright (c) 2017</p>
 *
 * @author yangpeng
 * @version 1.0
 * @date 2018/3/6
 * @since 1.8
 */
@Component
public class RequestUtil {
    @Autowired
    private CommonCacheUtil cacheUtil;

    public UserElement getCurrentUser() throws RongZheBusinessException {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String token = request.getHeader(Constants.REQUEST_TOKEN_KEY);
        if (StringUtils.isNotEmpty(token)) {
            try {
                UserElement ue = cacheUtil.getUserByToken(token);
                return ue;
            } catch (Exception e) {
                throw new RongZheBusinessException("登陆后再试");
            }
        }
        return null;
    }

    /**
     * 获取当前id
     * @return
     */
    public Integer getCurrentUserId() throws RongZheBusinessException {
        UserElement currentUser = getCurrentUser();
        if(null == currentUser){
            return null;
        }else{
            return currentUser.getUserId();
        }

    }

}
